package protocol

import (
	"bufio"
	"bytes"
	"encoding/binary"
)

func Encode(data string) ([]byte, error) {
	// 读取消息的长度并转换为int32（4个字节）
	var length = int32(len(data))
	var pkg = new(bytes.Buffer)
	// 写入消息头至缓冲区（小端方式
	err := binary.Write(pkg, binary.LittleEndian, length)
	if err != nil {
		return nil, err
	}
	// 写入消息实体至缓冲区
	binary.Write(pkg, binary.LittleEndian, []byte(data))
	if err != nil {
		return nil, err
	}
	return pkg.Bytes(), nil
}

func Decode(reader *bufio.Reader) (string, error) {
	// 读取消息长度
	lenOfByte, _ := reader.Peek(4)
	lenOfBuff := bytes.NewBuffer(lenOfByte)
	var length int32
	err := binary.Read(lenOfBuff, binary.LittleEndian, &length)
	if err != nil {
		return "", err
	}
	// buffer返回缓冲区中现有的可读取的字节数
	if int32(reader.Buffered()) < length+4 {
		return "", err
	}

	// 读取真正的消息数据
	pack := make([]byte, int(4+length))
	_, err = reader.Read(pack)
	if err != nil {
		return "", err
	}

	return string(pack[4:]), nil

}

func main() {

}
